<template>
  <view class="register-container">
    <!-- 标题 -->
    <view class="register-title">用户注册</view>
    <view class="register-subtitle">创建您的阅读账号</view>
    
    <!-- 用户名输入 -->
    <view class="input-group">
      <input 
        v-model="formData.username" 
        placeholder="请输入用户名" 
        class="input-box"
        :class="{'input-error': errors.username}"
        @blur="checkUsername"
      />
      <view v-if="errors.username" class="error-message">{{ errors.username }}</view>
      <view v-if="usernameChecking" class="checking-message">检查中...</view>
      <view v-if="usernameChecked && !errors.username" class="success-message">用户名可用</view>
    </view>
    
    <!-- 密码输入 -->
    <view class="input-group">
      <input 
        v-model="formData.password" 
        placeholder="请输入密码(至少6位)" 
        type="password"
        class="input-box"
        :class="{'input-error': errors.password}"
      />
      <view v-if="errors.password" class="error-message">{{ errors.password }}</view>
    </view>
    
    <!-- 确认密码输入 -->
    <view class="input-group">
      <input 
        v-model="formData.confirmPassword" 
        placeholder="请再次输入密码" 
        type="password"
        class="input-box"
        :class="{'input-error': errors.confirmPassword}"
      />
      <view v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</view>
    </view>
    
    <!-- 注册按钮 -->
    <button 
      @click="handleRegister"
      class="register-btn"
      :disabled="loading || !formValid"
      :style="{opacity: (loading || !formValid) ? 0.7 : 1}"
    >
      {{ loading ? '注册中...' : '立即注册' }}
    </button>
    
    <!-- 已有账号登录链接 -->
    <view class="login-link">
      已有账号? <text class="login-text" @click="goToLogin">立即登录</text>
    </view>
    
    <!-- 状态提示 -->
    <view v-if="message" class="message" :class="messageType">
      {{ message }}
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'

// API基础地址（根据实际修改）
const BASE_URL = 'HTTP://192.168.153.1:8080/users/register'

const formData = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const errors = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const loading = ref(false)
const message = ref('')
const messageType = ref('')
const usernameChecking = ref(false)
const usernameChecked = ref(false)

// 表单验证状态
const formValid = computed(() => {
  return formData.value.username && 
         formData.value.password && 
         formData.value.confirmPassword &&
         !errors.value.username &&
         !errors.value.password &&
         !errors.value.confirmPassword
})

/**
 * 检查用户名是否可用（兼容所有平台的请求方式）
 */
const checkUsername = async () => {
  if (!formData.value.username) {
    errors.value.username = '请输入用户名'
    usernameChecked.value = false
    return
  }
  
  if (formData.value.username.length < 3) {
    errors.value.username = '用户名至少3位'
    usernameChecked.value = false
    return
  }
  
  usernameChecking.value = true
  errors.value.username = ''
  usernameChecked.value = false
  
  try {
    const response = await uniRequest({
      url: '/user/login',
      method: 'GET',
      data: { username: formData.value.username }
    })
    
    if (response.data.exists) {
      errors.value.username = '用户名已存在'
    } else {
      usernameChecked.value = true
    }
  } catch (err) {
    console.error('检查用户名失败:', err)
    showMessage(`检查失败: ${err.message || err.errMsg || '未知错误'}`)
  } finally {
    usernameChecking.value = false
  }
}

/**
 * 处理注册提交
 */
const handleRegister = async () => {
  if (!validateForm()) return

  loading.value = true
  message.value = ''

  try {
    const response = await uniRequest({
      url: '/user/register',
      method: 'POST',
      data: {
        username: formData.value.username,
        password: formData.value.password
      }
    })
    
    if (response.data.code === 200) {
      showMessage('注册成功', 'success')
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
    } else {
      showMessage(response.data.message || '注册失败', 'error')
    }
  } catch (err) {
    console.error('注册请求失败:', err)
    showMessage(`注册失败: ${err.message || err.errMsg || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

/**
 * 封装的uni.request方法（解决兼容性问题）
 */
const uniRequest = (options) => {
  return new Promise((resolve, reject) => {
    const fullOptions = {
      ...options,
      url: BASE_URL + options.url,
      header: {
        'Content-Type': 'application/json',
        ...(options.header || {})
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res)
        } else {
          reject(new Error(res.data.message || `请求失败，状态码: ${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '网络请求失败'))
      }
    }
    
    uni.request(fullOptions)
  })
}

/**
 * 表单验证
 */
const validateForm = () => {
  let isValid = true
  errors.value = { username: '', password: '', confirmPassword: '' }
  
  // 用户名验证
  if (!formData.value.username.trim()) {
    errors.value.username = '请输入用户名'
    isValid = false
  } else if (formData.value.username.length < 3) {
    errors.value.username = '用户名至少3位'
    isValid = false
  }
  
  // 密码验证
  if (!formData.value.password) {
    errors.value.password = '请输入密码'
    isValid = false
  } else if (formData.value.password.length < 6) {
    errors.value.password = '密码长度不能少于6位'
    isValid = false
  }
  
  // 确认密码验证
  if (!formData.value.confirmPassword) {
    errors.value.confirmPassword = '请再次输入密码'
    isValid = false
  } else if (formData.value.password !== formData.value.confirmPassword) {
    errors.value.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }
  
  return isValid
}

/**
 * 跳转到登录页面
 */
const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  })
}

/**
 * 显示消息提示
 */
const showMessage = (msg, type = 'error') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}
</script>

<style>
.register-container {
  padding: 40rpx 60rpx;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.register-title {
  font-size: 48rpx;
  font-weight: bold;
  text-align: center;
  margin: 80rpx 0 20rpx;
  color: #333;
}

.register-subtitle {
  font-size: 28rpx;
  text-align: center;
  margin-bottom: 80rpx;
  color: #999;
}

.input-group {
  margin-bottom: 40rpx;
  position: relative;
}

.input-box {
  height: 100rpx;
  border: 1rpx solid #e6e6e6;
  border-radius: 12rpx;
  padding: 0 30rpx;
  font-size: 30rpx;
  width: 100%;
  box-sizing: border-box;
  background-color: #fff;
}

.input-box:focus {
  border-color: #3a7afe;
}

.input-error {
  border-color: #f56c6c;
}

.error-message {
  color: #f56c6c;
  font-size: 24rpx;
  margin-top: 10rpx;
  padding-left: 10rpx;
}

.checking-message {
  color: #909399;
  font-size: 24rpx;
  margin-top: 10rpx;
  padding-left: 10rpx;
}

.success-message {
  color: #67c23a;
  font-size: 24rpx;
  margin-top: 10rpx;
  padding-left: 10rpx;
}

.register-btn {
  height: 100rpx;
  line-height: 100rpx;
  background-color: #3a7afe;
  color: white;
  border-radius: 12rpx;
  font-size: 34rpx;
  margin: 60rpx 0 30rpx;
  border: none;
}

.register-btn:active {
  opacity: 0.8;
}

.login-link {
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

.login-text {
  color: #3a7afe;
  margin-left: 10rpx;
}

.message {
  margin-top: 30rpx;
  padding: 20rpx;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
}

.message.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.message.error {
  background-color: #fef0f0;
  color: #f56c6c;
}
</style>